<template>
  <div class="sdy-login">
    <Teleport to=".header">
      <header-com title="登录"></header-com>
    </Teleport>

    <van-form @failed="failedHandler" @submit="submitHandler">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="userInfo.loginname"
          label="用户名"
          label-width="100px"
          name="pattern"
          placeholder="请填写用户名"
          :rules="[{ pattern: /^\w{5,12}$/, message: '请输入正确用户名' }]"
        />
        <!-- 通过 validator 进行函数校验 -->
        <van-field
          v-model="userInfo.password"
          label="密 码"
          label-width="100px"
          name="validator"
          placeholder="请填写密码"
          :rules="[{ pattern: /^\w{6,12}$/, message: '请输入正确密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import HeaderCom from '@/components/header.vue'
import { ref } from 'vue'
import { showFailToast, showSuccessToast } from 'vant'
import { userLogin } from '@/apis/users'
import { useRouter } from 'vue-router'

// 准备一个用户登录信息的接口
interface Users {
  loginname: string
  password: string
}

interface ResponseInfo {
  code: string
  message: string
}

const $router = useRouter()

// 准备一个提交的用户信息
const userInfo = ref<Users>({ loginname: '', password: '' })

// 提交表单的方法
const submitHandler = async () => {
  // 发送请求
  const res = await userLogin(userInfo.value)

  // 判断结果
  if ((res as unknown as ResponseInfo).code === '10011' || (res as unknown as ResponseInfo).code === '10010') {
    showFailToast((res as unknown as ResponseInfo).message)
    return
  }

  // 登录成功
  showSuccessToast((res as unknown as ResponseInfo).message)

  // 把 token 和 id 存储到 localStorage
  window.localStorage.setItem('token', res.data.token)
  window.localStorage.setItem('user_id', res.data.userid)

  // 然后跳转路由
  setTimeout(() => {
    $router.push('/home')
  }, 1000)
}

// 表单验证失败
const failedHandler = () => {
  showFailToast('请按照规则填写表单')
}
</script>

<style lang="scss" scoped>
.sdy-login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
